// 包装事件触发函数
// 节流
function trottle(fn, delay) {
  let timer: null | NodeJS.Timeout = null;
  let last = +new Date();
  return function (...args) {
    if (timer) {
      // 对于没执行到的任务需要手动清除
      // 删除之前的任务
      clearTimeout(timer);
      timer = null;
    }
    const now = +new Date();
    const that = this;
    const duration = last + delay - now;
    if (duration > 0) {
      timer = setTimeout(() => {
        fn.apply(that, args);
        last = +new Date();
        timer = null;
      }, duration);
    } else {
      last = now;
      fn.apply(that, args);
    }
  };
}
//   仿节流函数
function doubleClick(fn, wait) {
  console.log("doubleclick");
  let formerClick: null | NodeJS.Timeout = null;
  let lastX = 0;
  let lastY = 0;
  return function (...args) {
    const { x, y } = args[0];
    const that = this;
    // 双击：距离和时间都成立
    if (formerClick && Math.abs(x - lastX) <= 10 && Math.abs(y - lastY) <= 10) {
      fn.apply(that, args);
      formerClick = null;
    } else {
      // 时间成立，距离不成立
      if (formerClick) {
        clearTimeout(formerClick);
        formerClick = null;
      }
      lastX = x;
      lastY = y;
      formerClick = setTimeout(() => {
        formerClick = null;
      }, wait);
    }
  };
}
export default doubleClick;
